package com.app.controller;

import cn.hutool.json.JSONObject;
import com.app.pojo.Share;
import com.app.pojo.Status;
import com.app.service.impl.ShareService;
import com.app.utils.TokenManager;
import com.bby.CookieUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("share")
public class ShareController {
    private final TokenManager tokenManager;
    private final ShareService shareService;

    public ShareController(TokenManager tokenManager, ShareService shareService) {
        this.tokenManager = tokenManager;
        this.shareService = shareService;
    }

    /**
     * 添加一个共享
     * @param share 保包含：path,permissions,password,timeout;
     * @return USER_NOT_SIGNED_IN，FAIL，SUCCESS,SHARE_ALREADY_EXIST
     */
    @RequestMapping("addShare")
    @ResponseBody
    String addShare(Share share, HttpServletRequest request){
        System.out.println("share====="+share);
        String userId=tokenManager.getUserId(CookieUtils.getValue(request.getCookies(),"token"));
        JSONObject jsonObject=new JSONObject();
        //是否未登录
        if (userId==null){
            jsonObject.set("status", Status.USER_NOT_SIGNED_IN);
            return jsonObject.toString();
        }else {
            share.setUserId(userId);
            jsonObject.set("status", shareService.addShare(share));
        }
        return jsonObject.toString();
    }
    /**
     * 删除一个共享
     * @param source 共享的地址
     * @return
     */
    @RequestMapping("del")
    @ResponseBody
    String addShare(String source, HttpServletRequest request, HttpServletResponse response){
        String userId=tokenManager.getUserId(CookieUtils.getValue(request.getCookies(),"token"));
        JSONObject jsonObject=new JSONObject();
        response.setContentType("application/json");
        //是否未登录
        if (userId==null){
            jsonObject.set("status", Status.USER_NOT_SIGNED_IN);
            return jsonObject.toString();
        }else {
            jsonObject.set("status", shareService.delShareByIdPath(userId,source));
        }
        return jsonObject.toString();
    }
}
